package com.wpen.unit.core;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.DisposableBean;

import com.wpen.unit.AppVariables;
import com.wpen.unit.service.RegistryService;
import com.wpen.unit.utils.SpringUtil;
import com.wpen.unit.web.WebVariables;
import com.wpen.unit.web.dto.AgentRegistryResponse;

import lombok.extern.slf4j.Slf4j;

/**
 * 5分钟重新注册-定时任务线程
 * 
 * @author Wang Peng
 * @date 2022-12-08
 */
@Slf4j
public class RegistryScheduleWorker implements DisposableBean {
	private static final RegistryScheduleWorker instance = new RegistryScheduleWorker();

	private RegistryScheduleWorker() {
	}

	public static RegistryScheduleWorker getInstance() {
		return instance;
	}

	private final long loopRead = 5 * 60 * 1000;

	private Thread registryThread;
	private volatile boolean healthThreadRunning = true;

	public void start() {
		log.info(this.getClass().getName() + " start...");

		registryThread = new Thread(new Runnable() {
			// 常驻在线子线程
			@Override
			public void run() {
				while (!AppVariables.kernelStarted) {
					// 容器没有完成启动，等待
					try {
						TimeUnit.MILLISECONDS.sleep(1000);
					} catch (InterruptedException e) {
						log.error(e.getMessage(), e);
					}
				}
				// 批次扫描线程
				while (healthThreadRunning) {
					// 每次执行耗时，毫秒
					long start = System.currentTimeMillis();
					try {
						RegistryService scheduleHandler = SpringUtil.getBean(RegistryService.class);
						AgentRegistryResponse agentRegistryResponse = scheduleHandler.registryMe();
						if (!WebVariables.RESPONSE_SUCC_CODE.equals(agentRegistryResponse.getCode())) {
							log.warn("Registry Service Exception>>" + agentRegistryResponse.getCode() + ":"
									+ agentRegistryResponse.getMsg());
						}
					} catch (Exception e) {
						log.error("Registry Thread Exception>" + e.getMessage(), e);
					} finally {
						try {
							long cost = System.currentTimeMillis() - start;
							TimeUnit.MILLISECONDS.sleep(loopRead - cost);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		});
		registryThread.setDaemon(true);
		registryThread.setName("agent-registry");
		registryThread.start();
		log.info(registryThread.getName() + " running...");

	}

	public void destroy() {
		healthThreadRunning = false;
		log.info(this.getClass().getName() + " bye..");
	}

}
